package cn.bdqn.t354.service.impl;

import cn.bdqn.t354.dao.UserDao;
import cn.bdqn.t354.entity.User;
import cn.bdqn.t354.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 *  这个类配合redisconfig类的cacheManager方法
 *  通过RedisCacheManager改变默认的序列化
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;
    @Resource
    RedisTemplate redisTemplate;

   /* @Override
    public User getUser(Long id) {
        User user = (User) redisTemplate.boundValueOps("user::" + id).get();
        if (user == null) {
            System.out.println("--从数据库中查询--");
            //模拟数据库查询的时间
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            user = userDao.findById(id).get();
            //存储到redis
            redisTemplate.boundValueOps("user::" + id).set(user);
        } else {
            System.out.println("--从redis查询--");
        }
        return user;
    }

    @Override
    public void addUser(User user) {
        userDao.save(user);
        redisTemplate.boundValueOps("user::" + user.getUsrId()).set(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.save(user);
        redisTemplate.boundValueOps("user::" + user.getUsrId()).set(user);
    }

    @Override
    public void deleteUser(Long id) {
        userDao.deleteById(id);
        redisTemplate.delete("user::" + id);
    }*/

//    @Cacheable(value = "user", keyGenerator = "keyGenerator")
    @Cacheable(value = "user", key = "'user::'+#id")
    @Override
    public User getUser(Long id) {
        System.out.println("--从数据库中查询--");
        //模拟数据库查询的时间
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User user = userDao.findById(id).get();
        return user;
    }

    @CachePut(value = "user", key = "#user.getUsrId()")
    @Override
    public User addUser(User user) {
        userDao.save(user);
        return user;
    }

    @CachePut(value = "user", key = "'user::'+#user.getUsrId()")
    @Override
    public User updateUser(User user) {
        userDao.save(user);
        return user;
    }

    @CacheEvict(value = "user", key = "'user::'+#id")
    @Override
    public void deleteUser(Long id) {
        userDao.deleteById(id);
    }

}
